package cn.edu.gmall.realtime.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;

public class DimUtil {
    public static JSONObject getDimInfo(String tableName, String id) {
        //创建 RedisKey
        StringBuilder redisKey = new StringBuilder(tableName).append(":").append(id);

        //获取 Redis 连接
        Jedis jedis = RedisUtil.getJedis();
        String dimJsonStr = jedis.get(redisKey.toString());

        //判断是否从 Redis 中查询到数据
        if (dimJsonStr != null && dimJsonStr.length() > 0) {
            jedis.close();
            return JSON.parseObject(dimJsonStr);
        }

        //查询 hbase 中的维度数据
        JSONObject dimJsonObj = MyHbaseUtil.get(tableName, id);

        //将数据写入 Redis
        jedis.set(redisKey.toString(), dimJsonObj.toString());
        jedis.expire(redisKey.toString(), 24 * 60 * 60);
        jedis.close();

        //返回结果
        return dimJsonObj;
    }

    //根据 key 让 Redis 中的缓存失效
    public static void deleteCached(String key) {
        try {
            Jedis jedis = RedisUtil.getJedis();
            // 通过 key 清除缓存
            jedis.del(key);
            jedis.close();
        } catch (Exception e) {
            System.out.println("缓存异常!");
            e.printStackTrace();
        }
    }
}
